<template>
  <div class="page-container ver-layout-center">
    <div class="hor-layout">
      <el-button type="warning" size="small" @click="showUploadDialog=true">选择并保存分组数据到浏览器本地</el-button>
      <el-button type="primary" size="small" @click="showLocalData=!showLocalData">显示/隐藏本地数据</el-button>
      <el-button type="danger" size="small" @click="clearLocalData">清空本地数据</el-button>
      <el-button type="info" size="small" @click="toGroupUserPath">跳转分班程序页面</el-button>
    </div>
    <div v-if="showLocalData">
      <div style="width:calc(100% - 20px);background: white;padding: 10px;border-radius: 10px">
        <code>
          userTableData:{{ localTableData }}
        </code>
        <br>
      </div>
      <el-table v-if="localTableData.length" :data="localTableData" border
                style="width: 100%;margin-top: 10px" size="small" max-height="330px">
        <el-table-column v-for="(item,index) in localTableFieldList" :key="index"
                         :label="item" :prop="item" align="center"></el-table-column>
      </el-table>
    </div>
    <!--  上传分组弹窗  -->
    <el-dialog :visible.sync="showUploadDialog" title="上传保存分组数据到浏览器本地" center width="60%">
      <div class="ver-layout">
        <div class="hor-layout-center" style="margin-top: -20px;margin-bottom: 20px">
          <el-upload class="upload" :limit="1" :show-file-list="false"
                     action="" :multiple="false" :on-change="importExcel"
                     accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
            <div class="hor-layout-center">
            <span v-if="excelFileName" style="font-size: 12px;color: #666666;margin-right: 10px">
              {{ excelFileName }}</span>
              <el-button type="primary" size="small">选择分组数据Excel</el-button>
            </div>
          </el-upload>
          <el-button size="small" type="text" class="excel-template" @click="downloadExcelTemplate">
            (Excel模板下载)
          </el-button>
        </div>
        <el-table v-if="tableData.length" :data="tableData" border style="width: 100%;" size="small" max-height="330px">
          <el-table-column v-for="(item,index) in tableFieldList" :key="index"
                           :label="item" :prop="item" align="center"></el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="saveDataLocal">保存到浏览器本地</el-button>
        <el-button size="small" type="info" @click="showUploadDialog=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import XLSX from 'xlsx'

export default {
  data() {
    return {
      tableFieldObj: {},//上传的表格表头数据
      tableData: [],//上传的表格数据
      excelFileName: "",
      //
      localTableFieldObj: {},//保存到本地的表头字段数据
      localTableData: [],//保存到本地的表格数据
      showUploadDialog: false,
      showLocalData: false,
    }
  },
  computed: {
    tableFieldList() {
      return Object.keys(this.tableFieldObj)
    },
    localTableFieldList() {
      return Object.keys(this.localTableFieldObj)
    },
  },
  mounted() {
    this.getLocalTableData()
  },
  methods: {
    downloadExcelTemplate() {
      let link = document.createElement("a");
      link.href = "https://mp-67dcfd0c-c143-49dd-81a6-3d6aabd6ef7b.cdn.bspapp.com/cloudstorage/学生随机分班结果模版.xlsx";
      link.style.display = "none"; //a标签隐藏
      link.download = '学生随机分班结果模版.xls';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link)
    },
    toGroupUserPath() {
      this.$router.push({path: '/groupUserNew'})
    },
    clearLocalData() {
      localStorage.removeItem("userTableData")
      localStorage.removeItem("userTableFieldObj")
      this.getLocalTableData()
      this.$message.success("清空成功！")
    },
    getLocalTableData() {
      this.localTableFieldObj = {}
      let localTableData = localStorage.getItem("userTableData")
      this.localTableData = localTableData && JSON.parse(localTableData) || []
      this.localTableData.forEach((tableItem) => Object.keys(tableItem).forEach(key => this.localTableFieldObj[key] = key))
    },
    saveDataLocal() {
      localStorage.setItem("userTableData", JSON.stringify(this.tableData))
      this.getLocalTableData()
      this.showUploadDialog = false
      this.$message.success("保存成功！")
    },
    // 导入表格
    importExcel(param) {
      this.excelFileName = param.name
      console.log("importExcel", param)
      this.tableData = []
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.file2Xce(param).then(data => {
        setTimeout(() => {
          console.log("importExcel====", data)
          loading.close()
          this.convertTable(data)
        }, 500)
      }).catch(error => {
        console.error(error)
        setTimeout(() => {
          loading.close()
        }, 500)
      });
    },
    convertTable(data) {
      if (data && data.length > 0) {
        let tableFieldObj = {}, tableData = data[0] && data[0].sheet && data[0].sheet.length && data[0].sheet || []
        tableData.forEach((tableItem) => Object.keys(tableItem).forEach(key => tableFieldObj[key] = key))
        let haveOtherKey = Object.keys(tableFieldObj).find(key => key.indexOf("男生组") === -1 && key.indexOf("女生组") === -1)
        if (haveOtherKey) {
          this.$message.warning("导入数据格式不正确！")
          return
        }
        this.tableFieldObj = tableFieldObj
        this.tableData = tableData
      }
    },
    /**
     *解析文件
     */
    file2Xce(file) {
      return new Promise(function (resolve,) {
        const reader = new FileReader();
        reader.onload = function (e) {
          const data = e.target.result;
          this.wb = XLSX.read(data, {type: "binary"});
          const result = [];
          this.wb.SheetNames.forEach(sheetName => {
            result.push({sheetName: sheetName, sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])});
          });
          resolve(result);
        };
        reader.readAsBinaryString(file.raw);
      });
    }
  }
}
</script>

<style scoped>
.excel-template {
  margin-left: 10px;
}
</style>